package com.ruoyi.baselibrary.infobaseindex.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.ruoyi.baselibrary.infobaseindex.domain.InfoBaseIndex;
import com.ruoyi.baselibrary.infobaseindex.domain.InfoBaseIndexDetail;
import com.ruoyi.baselibrary.infobaseindex.mapper.InfoBaseIndexDetailMapper;
import com.ruoyi.baselibrary.infobaseindex.mapper.InfoBaseIndexMapper;
import com.ruoyi.baselibrary.infobaseindex.service.IInfoBaseIndexService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 基础库-指标库Service业务层处理
 *
 * @author ruoyi
 * @date 2022-01-17
 */
@Service
public class InfoBaseIndexServiceImpl implements IInfoBaseIndexService {
    @Resource
    private InfoBaseIndexMapper infoBaseIndexMapper;
    @Resource
    private InfoBaseIndexDetailMapper infoBaseIndexDetailMapper;

    /**
     * 查询基础库-指标库
     *
     * @param id 基础库-指标库主键
     * @return 基础库-指标库
     */
    @Override
    public InfoBaseIndex selectInfoBaseIndexById(Long id) {
        return infoBaseIndexMapper.selectInfoBaseIndexById(id);
    }

    /**
     * 查询基础库-指标库列表
     *
     * @param infoBaseIndex 基础库-指标库
     * @return 基础库-指标库
     */
    @Override
    public List<InfoBaseIndex> selectInfoBaseIndexList(InfoBaseIndex infoBaseIndex) {
        return infoBaseIndexMapper.selectInfoBaseIndexList(infoBaseIndex);
    }

    /**
     * 新增基础库-指标库
     *
     * @param infoBaseIndex 基础库-指标库
     * @return 结果
     */
    @Override
    public int insertInfoBaseIndex(InfoBaseIndex infoBaseIndex) {
        infoBaseIndex.setCreateTime(DateUtils.getNowDate());
        infoBaseIndex.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        //读取这个文件 然后解析入库
        String fileUrl = infoBaseIndex.getFileUrl();
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(fileUrl, Constants.RESOURCE_PREFIX);

        //解析内容
        InputStream inputStream=null;
        try {
            inputStream=new FileInputStream(downloadPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(inputStream); //指定输入流
        // 读取第二行到最后一行数据  read读到了从第二行开始的每一行每一列的数据
        List<List<Object>> read = reader.read(1, reader.getRowCount(), true);
        //存数据到实体类
        InfoBaseIndexDetail detail = new InfoBaseIndexDetail();

        for (int i = 0; i < read.size(); i++) {
            List<Object> objects = read.get(i);
            if(!objects.isEmpty()){
                //判断文件
                if(i==0){
                    Object name=objects.get(0);
                    if(!"一级指标".equals(name)){
                        throw new RuntimeException("请使用正确模板文件！");
                    }
                    infoBaseIndexMapper.insertInfoBaseIndex(infoBaseIndex);
                }
                //判断第几行获取数据
                if (i >= 1 && i < read.size()) {
                    //第八行数据（指标）
                    Object yjzb = objects.get(0);//一级指标
                    Object ejzb = objects.get(1); //二级指标
                    Object sjzb = objects.get(2);//三级指标
                    Object zbjs = objects.get(3); //指标解释
                    Object pfbz = objects.get(4); //评分标准
                    Object zbxz = objects.get(5); //指标性质
                    //指标文件编号index_id
                    Long indexId=infoBaseIndex.getId();
                    detail.setIndexId(indexId);
                    //文件名index_name
                    Object indexName=infoBaseIndex.getFileName();
                    detail.setIndexName(indexName.toString());
                    detail.setTargetOne(yjzb.toString());
                    detail.setTargetTwo(ejzb.toString());
                    detail.setTargetName(sjzb.toString());
                    detail.setTargetExplain(zbjs.toString());
                    detail.setTargetDesc(pfbz.toString());
                    detail.setTargetApply(zbxz.toString());
                    infoBaseIndexDetailMapper.insertInfoBaseIndexDetail(detail);
                }
            }
        }
        return 1;
    }

    /**
     * 解析指标数据集
     *
     * @param file
     * @return
     */
    private List<InfoBaseIndexDetail> analysisExcel(File file) {
        List<InfoBaseIndexDetail> infoBaseIndexDetails = new ArrayList<>();
        //读取文件单元格 判断第一个单元格值是否为 一级指标
        ExcelReader reader = ExcelUtil.getReader(file);
        //1.先从第一行读取
        List<List<Object>> read = reader.read(0);
        boolean oneTarget = isOneTarget(read);
        if (!oneTarget) {
            //不是一级指标
            //从第二行开始读取
            read = reader.read(1);
            boolean oneTarget1 = isOneTarget(read);
            if (!oneTarget1) {
                //还不是一级指标 抛出异常
                throw new ServiceException("请使用正确模板文件");
            }
        }
        for (List<Object> objects : read) {
            InfoBaseIndexDetail infoBaseIndexDetail = new InfoBaseIndexDetail();
            List<String> values = new ArrayList<>();
            for (Object object : objects) {
                //object 为每一个单元格的值
                values.add(object.toString());
            }
            if (values.size()==8){
                infoBaseIndexDetail.setIndexName(values.get(0));
                infoBaseIndexDetail.setIndexName(values.get(1));
                infoBaseIndexDetail.setIndexName(values.get(2));
                infoBaseIndexDetail.setIndexName(values.get(3));
                infoBaseIndexDetail.setIndexName(values.get(4));
                infoBaseIndexDetail.setIndexName(values.get(5));
                infoBaseIndexDetail.setIndexName(values.get(6));
                infoBaseIndexDetail.setIndexName(values.get(7));
            }
        }
        //开始解析文件
        return null;
    }

    /**
     * 判断第一个框是不是
     *
     * @param read
     */
    public boolean isOneTarget(List<List<Object>> read) {
        for (List<Object> objects : read) {
            if (objects.size() != 0) {
                Object o = objects.get(0);
                if (o.toString().equals("一级指标")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 修改基础库-指标库
     *
     * @param infoBaseIndex 基础库-指标库
     * @return 结果
     */
    @Override
    public int updateInfoBaseIndex(InfoBaseIndex infoBaseIndex) {
        infoBaseIndex.setUpdateTime(DateUtils.getNowDate());
        infoBaseIndex.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        return infoBaseIndexMapper.updateInfoBaseIndex(infoBaseIndex);
    }

    /**
     * 批量删除基础库-指标库
     *
     * @param ids 需要删除的基础库-指标库主键
     * @return 结果
     */
    @Override
    public int deleteInfoBaseIndexByIds(Long[] ids) {
        infoBaseIndexDetailMapper.deleteInfoBaseIndexDetailByIdss(ids);
        return infoBaseIndexMapper.deleteInfoBaseIndexByIds(ids);
    }

    /**
     * 删除基础库-指标库信息
     *
     * @param id 基础库-指标库主键
     * @return 结果
     */
    @Override
    public int deleteInfoBaseIndexById(Long id) {
        return infoBaseIndexMapper.deleteInfoBaseIndexById(id);
    }

    @Override
    public int insertInfoBaseIndexs(InfoBaseIndex infoBaseIndex) {
        infoBaseIndex.setCreateTime(DateUtils.getNowDate());
        infoBaseIndex.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        //读取这个文件 然后解析入库
        String fileUrl = infoBaseIndex.getFileUrl();
        // 本地资源路径
        String localPath = RuoYiConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(fileUrl, Constants.RESOURCE_PREFIX);
        // 还得加类型字段区分（setValue"部门"）
        infoBaseIndex.setFileType("项目");
        infoBaseIndexMapper.insertInfoBaseIndex(infoBaseIndex);
        //解析内容
        InputStream inputStream=null;
        try {
            inputStream=new FileInputStream(downloadPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(inputStream); //指定输入流
        // 读取第二行到最后一行数据  read读到了从第二行开始的每一行每一列的数据
        List<List<Object>> read = reader.read(1, reader.getRowCount(), true);
        //存数据到实体类
        InfoBaseIndexDetail detail = new InfoBaseIndexDetail();

        for (int i = 0; i < read.size(); i++) {
            List<Object> objects = read.get(i);
            //判断第几行获取数据
            if (i >= 1 && i < read.size()) {
                //第八行数据（指标）
                Object yjzb = objects.get(0);//一级指标
                Object ejzb = objects.get(1); //二级指标
                Object sjzb = objects.get(2);//三级指标
                Object zbjs = objects.get(3); //指标解释
                Object pfbz = objects.get(4); //评分标准
                Object zbxz = objects.get(5); //指标性质
                //指标文件编号index_id
                Long indexId=infoBaseIndex.getId();
                detail.setIndexId(indexId);
                //文件名index_name
                Object indexName=infoBaseIndex.getFileName();
                detail.setIndexName(indexName.toString());
                detail.setTargetOne(yjzb.toString());
                detail.setTargetTwo(ejzb.toString());
                detail.setTargetName(sjzb.toString());
                detail.setTargetExplain(zbjs.toString());
                detail.setTargetDesc(pfbz.toString());
                detail.setTargetApply(zbxz.toString());
                infoBaseIndexDetailMapper.insertInfoBaseIndexDetail(detail);
            }
        }
        return 1;
    }

    @Override
    public List<InfoBaseIndex> getIndexList(InfoBaseIndex infoBaseIndex){
       return infoBaseIndexMapper.selectIndexList(infoBaseIndex);
    }

    @Override
    public int editInfoBaseIndexName(InfoBaseIndex infoBaseIndex) {
       //修改主表名称
        infoBaseIndexMapper.updateInfoBaseIndex(infoBaseIndex);
        //修改子表名称
        infoBaseIndexDetailMapper.updateInfoBaseIndexDetailName(infoBaseIndex.getId(),infoBaseIndex.getFileName());

        return 1;
    }
}
